<?php if ( ! defined('BASEPATH')) exit('No direct script access allowed');

/*帐号相关控制器*/
class Account extends MY_Controller {
    public function __construct()
    {
        
        parent::__construct();
        $this->__validation();
        $this->load->model('Account_model','Account');
        $this->load->library('memcachedhelper');
    }
    public function index()
    {
        
    }

    
    public function checkAccount()
    {
        if(empty($this->params['account']))
        {
            $this->setResponse('ACCOUNT_IS_EMPTY');
        }
        else
        {
            $rtn = $this->Account->checkAccount($this->params['account']);
            $this->response['code'] = 0;
            $this->response['message'] = '';
            $this->response['data'] = $rtn ? TRUE : FALSE;
        }
        $this->_print();

    }
        
    public function get()
    {
        if(is_numeric($this->params['uid']) && $this->params['uid']>0)
        {
            $rtn = $this->Account->getMemberById($this->params['uid']);
            if($rtn)
            {
                $this->response['code'] = 0;
                $this->response['message'] = '';
                $this->response['data'] = $this->__formatMicroUser($rtn);
            }
            else
                $this->setResponse('USER_IS_NOT_FOUND');
        }
        else
        {
            $this->setResponse('USER_ID_IS_EMPTY');
        }
        $this->_print();
    }
    

    public function modifypasswd()
    {
        if(!is_numeric($this->params['uid']))
        {
            $this->setResponse('USER_ID_IS_EMPTY');
            $this->_print();
            return;
        }
        $member = $this->Account->getMemberById($this->params['uid']);
        if($member)
        {

            if(md5($this->params['oldpassword'].$member->slat)!=$member->passwd)
            {
                $this->setResponse('OLDPASSWD_IS_ERROR');
                $this->_print();
                return;
            }
             $this->load->helper('string');
            $slat = random_string('alnum',10);
            $passwd = md5($this->params['newpassword'].$slat);
            $this->Account->modifypasswd($this->params['uid'],$passwd,$slat);
            $this->response['code'] = 0;
            $this->response['message'] = 'OK';
        }
        else
        {
             $this->setResponse('USER_IS_NOT_FOUND');
        }
        $this->_print();
    }

    public function create()
    {
        $this->load->helper('string');
        $slat = random_string('alnum',10);
        if(empty($this->params['account']))
        {
            $this->setResponse('ACCOUNT_IS_EMPTY');
            $this->_print();
            return;
        }
        $this->load->helper('utility');
        if(!is_account($this->params['account']))
        {
            $this->setResponse('ACCOUNT_IS_NOT_MATCH');
            $this->_print();
            return;
        }
        if(empty($this->params['password']))
        {
            $this->setResponse('PASSWD_IS_EMPTY');
            $this->_print();
            return;
        }
        if($this->Account->checkAccount($this->params['account']))
        {
            $this->setResponse('ACCOUNT_IS_EXISTS');
            $this->_print();
            return;
        }
        $password = md5($this->params['password'].$slat);
        $accountinfo = array(
            'account'=>$this->params['account'],
            'passwd'=>$password,
            'slat'=>$slat,
            'username'=>'',
            'createtime'=>time(),
            'createip'=>$this->params['ip'],
            'credit'=>0,
            'realname'=>'',
            'gender'=>0,
            'birthday'=>'0000-00-00',
            'email'=>'',
            'emaiisverify'=>0,
            'mailverifytime'=>0,
            'mobile'=>'',
            'mobileisverify'=>0,
            'userface'=>'',
            'location'=>'',
            'logincount'=>1,
            'lastlogintime'=>time(),
            'lastloginip'=>$this->params['ip'],
            'fromid'=>'cctv',
        );
        $result = $this->Account->create($accountinfo);
        if($result)
        {
            $this->response['code'] = 0;
            $this->response['message']='OK';
            $this->response['data'] = array('uid'=>$result,'account'=>$this->params['account']);
        }
        else
        {
             $this->setResponse('SERVER_IS_ERROR');
        }
        $this->_print();
    }
    

    function __createtoken($userinfo)
    {
        $token = strtolower(md5($userinfo['uid'].$userinfo['ip']));

        $this->memcachedhelper->set($token,$userinfo,86300);
        return $token;
    }

    function validationECard()
    {
        $rtn =$this->Account->getUserECard($this->params['uid']);
        if($rtn)
        {
            if($rtn->createtime+$rtn->expire*86400<time())
            {
                $this->setResponse('ECARD_EXPIRE');

                $this->_print();
                return;
            }
            if(strlen($this->params['input'])==4)
            {
                $cachevalue = $this->memcachedhelper->get('ecard_'.$this->params['uid']);
                if($cachevalue)
                {
                    $codes = unserialize($rtn->code);
                    if(($codes[substr($cachevalue,0,2)].$codes[substr($cachevalue,2,2)]) == $this->params['input'])
                    {
                        //密保卡验证成功
                        $rtn = $this->Account->getMemberById($this->params['uid']);
                        $userinfo =  $this->__formatMicroUser($rtn);
                        $token = $this->__createtoken($userinfo);
                        $this->response['code'] = 0;
                        $this->response['data'] = array_merge($userinfo,array('token'=>$token));
                        $this->Account->updateLoginTime($rtn->uid,$this->params['ip']);
                    }
                    else
                    {
                        $this->setResponse('ECARD_VALIDATION_ERROR');
                    }
                }
                else
                {
                    $this->setResponse('ECARD_VALIDATION_TIMEOUT');
                }
            }
            else
            {
                $this->setResponse('ECARD_VALUE_ERROR');
            }
        }
        else
        {
            $this->setResponse('ECARD_VALUE_ERROR');
        }
        $this->_print();
    }


    /*用户认证*/
    public function auth()
    {

        if(empty($this->params['ip']) || !is_ip($this->params['ip']))
        {
             $this->setResponse('IP_IS_NO_VALID');
             $this->_print();
             return;
        }
        if(empty($this->params['account']) || empty($this->params['password']))
        {
            $this->setResponse('PASSWD_IS_EMPTY');
           
            $this->_print();
            return;
        }

        $rtn = array();
        if($this->__checkfailedlogincount($this->params['ip']))
        {

             $this->setResponse('LOGIN_FAILED_MAX');
             $this->_print();

             return;
        }
        if(!is_numeric($this->params['account']))
        {
            $rtn = $this->Account->getMemberByAccount($this->params['account']);
        }
        else
            $rtn = $this->Account->getMemberById($this->params['account']);

        if($rtn)
        {
            if($rtn->status!=0)
            {
                $this->setResponse('USER_LOCKED');
                 $this->_print();
                 return;
            }
            if($rtn->passwd===md5($this->params['password'].$rtn->slat))
            {
                
                $userinfo =  $this->__formatMicroUser($rtn);
                $userinfo['ip'] = $this->params['ip'];
                $token = $this->__createtoken($userinfo);
                unset($userinfo['ip']);
                $this->response['code'] = 0;
                $this->response['data'] = array_merge($userinfo,array('token'=>$token));
                if($this->Account->getUserECard($rtn->uid))
                {
                    $this->setResponse('REQUIRE_ECARD',array('token'=>$token,'ecard'=>$this->__generateECard($rtn->uid),'uid'=>$rtn->uid));
                    $this->_print();
                    return;
                }
                $this->Account->updateLoginTime($rtn->uid,$this->params['ip']);

            }
            else
            {
                $this->__setfailedlogincount($this->params['ip']);
                $this->setResponse('LOGIN_FAILED');

            }
        }
        else
        {
            $this->__setfailedlogincount($this->params['ip']);
            
            $this->setResponse('LOGIN_FAILED');
        }
        
        $this->_print();
    }

    private function __generateECard($uid)
    {
        $cachekey = 'ecard_'.$uid;
        $letter = 'ABCDEFGH';
        $numeric = '0123456789';
        $num =  substr($letter,rand(0,strlen($letter)-1),1).substr($numeric,rand(0,strlen($numeric)-1),1).substr($letter,rand(0,strlen($letter)-1),1).substr($numeric,rand(0,strlen($numeric)-1),1);
        $this->memcachedhelper->set('ecard_'.$uid,$num,3600);
        return $num;
    }
    
    /*绑定安全卡*/
    public function bindecard()
    {

        $rtn =$this->Account->getUserECard($this->params['uid']); 

        if($rtn)
        {
            $this->setResponse('ECARD_EXISTS',array('sn'=>$rtn->sn));
        }
        else
        {
            $this->load->library('ecardcore');
            $cardinfo = array();
            $this->ecardcore->uid=$this->params['uid'];
            $this->ecardcore->generateCode();
            $this->ecardcore->generateSN();
            $this->ecardcore->expire = date('r',time()+90*86400);
            $cardinfo['code']  = $this->ecardcore->code;
            $cardinfo['sn'] = $this->ecardcore->sn;
            $cardinfo['sn'] = preg_replace('/ /','',$cardinfo['sn']);
            $cardinfo['uid'] = $this->params['uid'];
            
            $this->Account->bindECard($cardinfo);
            $this->response['code'] = 0;
            $this->response['data']['sn'] = $cardinfo['sn'];
        }
        $this->_print();
    }

    /*解除安全卡绑定*/
    public function unbindecard()
    {
        $rtn =$this->Account->getUserECard($this->params['uid']); 
        if(!$rtn)
        {
            $this->setResponse('ECARD_NOT_EXISTS');

        }
        else
        {
            $rtn = $this->Account->unBindECard($this->params['uid'],$this->params['sn']);
            if($rtn)
            {
                $this->response['code'] = 0;
                $this->response['message'] = '解绑成功';
            }
            else
            {
                $this->setResponse('ECARD_REMOVE_FAILED');
            }
        }
        $this->_print();
    }

    private function __checkfailedlogincount($ip)
    {
        $key = 'loginfailed_'.$ip;
       
        $cache = $this->memcachedhelper->get($key);
        if($cache)
        {
            return (int)$cache['failedcount']>5;
        }
        return FALSE;
    }

    private function __setfailedlogincount($ip,$num = 1)
    {
        $key = 'loginfailed_'.$ip;
        $this->load->library('memcachedhelper');
        $cache = $this->memcachedhelper->get($key);
        if($cache)
        {
            $cache['failedcount'] = $cache['failedcount']+$num;
            $cache['lasttime'] = date('r');
            $this->memcachedhelper->set($key,$cache,600);
        }
        else
        {
            $cache['failedcount'] = $num;
            $cache['lasttime'] = date('r');
            $this->memcachedhelper->set($key,$cache,600);
        }
    }


    private function __formatMicroUser($data)
    {
        if(!$data) return NULL;
        if(is_array($data))
        {
             return array(
                    'uid'=>(int)$data['uid'],
                    'username'=>$data['username'],
                    'createtime'=>(int)$data['createtime'],
                    'credit'=>(int)$data['credit'],
                    'gender'=>(int)$data['gender'],
                    'birthday'=>$data['birthday'],
                    'userface'=>$data['userface'],
                    'location'=>$data['location']
                );
        }
        else
        {
            return array(
                    'uid'=>(int)$data->uid,
                    'username'=>$data->username,
                    'createtime'=>(int)$data->createtime,
                    'credit'=>(int)$data->credit,
                    'gender'=>(int)$data->gender,
                    'birthday'=>$data->birthday,
                    'userface'=>$data->userface,
                    'location'=>$data->location
                );
        }
    }


    

}

